import { Component, OnInit, ViewChild } from '@angular/core';

import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { LevelSearchComponent } from 'src/app/share/level-search/level-search.component';
import { OrganizationSearchComponent } from 'src/app/share/organization-search/organization-search.component';

import { SetModelPermissionComponent } from 'src/app/share/set-model-permission/set-model-permission.component';
import { SetDataPermissionComponent } from 'src/app/share/set-data-permission/set-data-permission.component';
import {
  JoblevelService,
  OrganizationPositionLevel,
  OrganizationService,
  PositionLevel,
  OrganizationPositionLevelPK
} from 'sparrow-permission-lib';
import { FlatNode } from 'src/app/domain/flat-node';
import { DynamicDataSourceForNzTreeService } from 'src/app/service/dynamic-data-source-for-nz-tree.service';
import { NzTreeCommonService } from 'src/app/service/nz-tree-common.service';
import { NzTreeGetChildren } from 'src/app/service/nz-tree-get-children';
import { NzTreeGetRoleChildrenService } from 'src/app/service/nz-tree-get-role-children.service';
import { NzTreeGetLevelChildrenService } from 'src/app/service/nz-tree-get-level-children.service';
import { combineAll, map, switchMap, tap } from 'rxjs/operators';
import { combineLatest, concat, merge, zip } from 'rxjs';

@Component({
  selector: 'app-level',
  templateUrl: './level.component.html',
  styleUrls: ['./level.component.css'],
})
export class LevelComponent implements OnInit {
  modelName?: string;
  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private levelService: JoblevelService,
    private orgService: OrganizationService
  ) {}
  dataSource: any;
  hasChild = (_: number, node: FlatNode) => node.expandable;
  treeService: NzTreeCommonService = new NzTreeCommonService();

  ngOnInit(): void {
    let getChildrenService: NzTreeGetChildren =
      new NzTreeGetLevelChildrenService(this.levelService, this.orgService);
    getChildrenService
      .getChildren({
        id: 'root',
        label: 'root',
        level: -1,
        expandable: true,
        type: 'ORG',
      })
      .subscribe(
        (res) => {
          this.dataSource = new DynamicDataSourceForNzTreeService(
            this.treeService.treeControl,
            res,
            getChildrenService
          );
        },
        (error) => {
          this.message.error('初始化失败！' + error);
        }
      );
  }

  selectedLevel!: PositionLevel | any;
  onItemSelect(node: FlatNode): void {
    console.log(node)
    this.treeService.selectListSelection.toggle(node);
    const parents$=this.levelService.getParents2(node.orgId! + '_' + node.id).pipe(
      switchMap((parentOrgLevels: any[]) =>
        zip(
          ...parentOrgLevels.map(
            (orgLevel:  any) =>
              this.levelService.get6(orgLevel.id.positionLevelId).pipe(
                map((parentLevel) => {
                  return { ...parentLevel, orgId: orgLevel.id.organizationId };
                }),
              )
          )
        )
      ),
      tap(parentLevels=>console.log(parentLevels)),
    )

    const level$= this.levelService
      .get6(node.id)
      .pipe(
        //获取上级组织
        switchMap((level) =>
          this.levelService.getParentOrganizations1(node.id).pipe(
            map((orgs) => {
              return { ...level, parentOrgs: orgs, orgId: node.orgId };
            }),
            tap(sss=>console.log(sss))
          )
        ),
      )

      level$
      .subscribe((res) => {
        this.selectedLevel = res;
        parents$.subscribe(parents=>{
          this.selectedLevel.parents=parents
        })
        console.log(res)
      },
      (error)=>{
        console.log(error)
      });
  }

  // for new organization
  isNewVisible: boolean = false;
  validateForm!: FormGroup;

  @ViewChild(OrganizationSearchComponent)
  organizationSearch!: OrganizationSearchComponent;
  submitForm() {
    if (!this.validateForm.valid) {
      // console.log(this.validateForm.)
      for (const i in this.validateForm.controls) {
        if (this.validateForm.controls.hasOwnProperty(i)) {
          this.validateForm.controls[i].markAsDirty();
          this.validateForm.controls[i].updateValueAndValidity();
          console.log(i);
        }
      }
    } else {
      let level: any = this.validateForm.value;
      const organizations$: any = this.organizationSearch.selectedParent.map(
        (p) => p.id
      );
      level.organizationIds = organizations$;
      level.isRoot = true;
      this.levelService.create6(level).subscribe((res) => {
        this.levelService.setParentOrg1(res.id!, organizations$).subscribe();
        this.message.success('添加成功！');
        this.isNewVisible = false;
      });
    }
  }

  showNew(node: FlatNode | null) {
    if (node === null) {
      this.validateForm = this.fb.group({
        name: [null, [Validators.required]],
        code: [null, [Validators.required]],
      });
    } else {
      this.validateForm = this.fb.group({
        name: [node.me.name, [Validators.required]],
        code: [node.me.code, [Validators.required]],
      });
    }

    this.isNewVisible = true;
  }

  isReportLineVisible = false;
  showReportLine() {
    this.isReportLineVisible = true;
  }

  isRoleReportTree = false;
  showReportRoleTree() {
    this.isRoleReportTree = true;
  }

  @ViewChild(LevelSearchComponent) levelSearch!: LevelSearchComponent;
  saveReportLine() {
    let organizationRelation: OrganizationPositionLevelPK[] = [];
    this.levelSearch.treeService.selectListSelection.selected
      .forEach((f) => {
        organizationRelation.push(
          { positionLevelId: f.id, organizationId: f.orgId }
        );
      });
    this.levelService.addRelation(this.selectedLevel.orgId + '_' + this.selectedLevel.id, organizationRelation).subscribe((res) => {
      this.isReportLineVisible = false;
    });
  }

  delete(node: any) {
    this.levelService.delete6([node.id],'response').subscribe(res=>{
      if(res.status===204){
        this.message.success('删除成功！')
      }
    })
  }

  handleCancel() {
    this.isNewVisible = false;
    this.isReportLineVisible = false;
    this.isRoleReportTree = false;
  }

  showParentOrgs(){

  }

  // 取消组织关系，上级
  onTagClose(s: any) {
    this.levelService
        .removeRelation(this.selectedLevel.orgId + '_' +this.selectedLevel.id, [{organizationId: s.orgId,positionLevelId:s.id}])
        .subscribe((res) => {
          this.message.success('成功取消上级！');
        });
  }
}
